package com.bee.oa.web.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.bee.base.entity.ExtTreeStore;
import com.bee.base.util.BaseConstants;
import com.bee.base.util.CriteriaConstants;
import com.bee.oa.domain.sm.Parameter;
import com.bee.oa.domain.sm.Resource;
import com.bee.oa.service.sm.ParameterService;
import com.bee.oa.service.sm.ResourceService;

@Controller
@RequestMapping("/sm")
public class SmController {

	@Autowired
	private ParameterService parameterService;

	@Autowired
	private ResourceService resourceService;

	@RequestMapping(value = "/findParameter", method = RequestMethod.POST)
	@ResponseBody
	public List<Parameter> findParameter(@RequestParam Map<String, String> params) {
		params.clear();
		params.put(CriteriaConstants.EQ + CriteriaConstants.SPLIT + BaseConstants.STATUS, "1");
		return parameterService.find(params);
	}

	@RequestMapping(value = "/findResource", method = RequestMethod.POST)
	@ResponseBody
	public List<ExtTreeStore> findResource(@RequestParam Map<String, Object> params) {
		return this.generateTree(Long.valueOf(params.get(BaseConstants.PARENT_SID).toString()));
	}

	private List<ExtTreeStore> generateTree(Long parentSid) {
		// 查询
		Map<String, String> params = new HashMap<String, String>();
		params.put(CriteriaConstants.EQ + CriteriaConstants.SPLIT + BaseConstants.STATUS, "1");
		params.put(CriteriaConstants.EQ + CriteriaConstants.SPLIT + BaseConstants.PARENT_SID, String.valueOf(parentSid));
		params.put(CriteriaConstants.ASC + CriteriaConstants.SPLIT + BaseConstants.SORT, "1");
		List<Resource> list = resourceService.find(params);

		// 生成
		List<ExtTreeStore> result = new ArrayList<ExtTreeStore>();
		for (Resource r : list) {
			ExtTreeStore extTreeStore = new ExtTreeStore();
			extTreeStore.setId(r.getSid());
			extTreeStore.setText(r.getCname());
			extTreeStore.setLink(r.getLink());
			if (r.getIsLeaf().equals(1)) {
				extTreeStore.setLeaf(true);
			} else {
				extTreeStore.setLeaf(false);
				extTreeStore.setExpanded(true);
				extTreeStore.setChildren(this.generateTree(r.getSid()));
			}
			result.add(extTreeStore);
		}
		return result;
	}

}
